package com.mingda.weathermagiccenter.utils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSONArray;
import com.mingda.weathermagiccenter.config.LegendHumiConfig;
import com.mingda.weathermagiccenter.config.LegendPrec10daysConfig;
import com.mingda.weathermagiccenter.config.LegendPrec3monthsConfig;
import com.mingda.weathermagiccenter.config.LegendPrecAllConfig;
import com.mingda.weathermagiccenter.config.LegendPrecConfig;
import com.mingda.weathermagiccenter.config.LegendTemConfig;
import com.mingda.weathermagiccenter.config.LegendWaterrateConfig;
import com.mingda.weathermagiccenter.config.LegendWaterrateinsideConfig;
import com.mingda.weathermagiccenter.config.LegendWaterrateoutConfig;
import com.mingda.weathermagiccenter.config.LegendWindConfig;
import com.mingda.weathermagiccenter.config.LegendPresConfig;

public class WeatherDataProcessor {

    /**
     * 处理不同类型气象数据的主方法
     *
     * @param data 原始数据，包含data和各类legend字段
     * @param type 数据类型：temp(温度)、prec(降水)、humi(湿度)、pres(气压)、wind(风速)、 waterrate(土壤含水率)、waterrate_out_plant(地表覆盖物表面湿度)、waterrate_inside_plant(地表覆盖物内部湿度)
     * @return 处理结果对象
     */
    public static ProcessedWeatherData setDataByType(Map<String, Object> data, String type) {
        ProcessedWeatherData result = new ProcessedWeatherData();
        
        try {
            switch (type) {
                case "temp":
                    processTemperatureData(data, result);
                    break;
                case "prec":
                    processPrecipitationData(data, result);
                    break;
                case "humi":
                    processHumidityData(data, result);
                    break;
                case "pres":
                    processPressureData(data, result);
                    break;
                case "wind":
                    processWindData(data, result);
                    break;
                case "waterrate" :
                    processWaterrateData(data, result);
                    break;
                case "waterrateout" :
                    processWaterrateoutData(data, result);
                    break;
                case "waterrateinside" :
                    processWaterrateinsideData(data, result);
                    break;
                case "rainfall12hour" :
                    processRainfall12hourData(data, result);
                    break;
                case "rainfall24hour" :
                    processRainfall24hourData(data, result);
                    break;
                case "rainfall10day" :
                    processRainfall10dayData(data, result);
                    break;
                case "rainfall3month" :
                    processRainfall3monthData(data, result);
                    break;
                case "winddeck":
                    processWinddeckData(data, result);
                    break;
                default:
                    throw new IllegalArgumentException("Unsupported weather type: " + type);
            }
        } catch (Exception e) {
            // 记录日志
            System.err.println("Error processing weather data type: " + type + ", error: " + e.getMessage());
            // 确保返回有效对象
            result.weatherData = new JSONArray();
            result.legend = new JSONArray();
            result.interval = new JSONArray();
        }
        
        return result;
    }

    /**
     * 处理温度数据
     */
    private static void processTemperatureData(Map<String, Object> data, ProcessedWeatherData result) {
        List<Map<String, Object>> dataList = safeGetList(data, "data");
        
        // 获取所有有效温度数据
        List<BasicDataPoint> allValidTemps = dataList.stream()
            .filter(Objects::nonNull)
            .filter(item -> {
                Object tempValueObj = item.get("temp");
                if (tempValueObj == null) return false;
                
                Float tempValue = convertToFloat(tempValueObj);
                return tempValue != null && 
                       tempValue != 999999f && 
                       tempValue >= -50f && 
                       tempValue <= 60f;
            })
            .map(item -> new BasicDataPoint(
                convertToFloat(item.get("lon")),
                convertToFloat(item.get("lat")),
                convertToFloat(item.get("temp"))
            ))
            .filter(point -> point.lon != null && point.lat != null && point.value != null)
            .collect(Collectors.toList());

        if (allValidTemps.isEmpty()) {
            result.weatherData = new JSONArray();
            result.legend = new JSONArray();
            result.interval = new JSONArray();
            return;
        }

        // // 计算平均温度
        // double avgTemp = allValidTemps.stream()
        //     .mapToDouble(point -> point.value)
        //     .average()
        //     .orElse(0);

        // // 计算标准差
        // double stdDev = 0;
        // if (!allValidTemps.isEmpty()) {
        //     final double finalAvgTemp = avgTemp;
        //     double variance = allValidTemps.stream()
        //         .mapToDouble(point -> Math.pow(point.value - finalAvgTemp, 2))
        //         .average()
        //         .orElse(0);
        //     stdDev = Math.sqrt(variance);
        // }

        // // 方差滤波 - 使用3倍标准差而不是5倍，避免过滤过多数据
        // final double finalAvgTemp = avgTemp;
        // final double finalStdDev = stdDev;
        // List<BasicDataPoint> filteredData = allValidTemps.stream()
        //     .filter(temp -> Math.abs(finalAvgTemp - temp.value) <= 5 * finalStdDev)
        //     .collect(Collectors.toList());

        result.weatherData = new JSONArray();
        for (BasicDataPoint point : allValidTemps) {
            Map<String, Object> pointMap = new HashMap<>();
            pointMap.put("lon", point.lon);
            pointMap.put("lat", point.lat);
            pointMap.put("value", Math.round(point.value * 10) / 10.0); // 保留一位小数
            result.weatherData.add(pointMap);
        }

        // 处理图例 - 使用安全获取方法
        result.legend = safeGetLegend(data, "legendtem");
        // 计算合适的区间
        result.interval = calculateIntervals(result.weatherData, result.legend, 1.0, "temp");
    }

    /**
     * 处理湿度数据
     */
    private static void processHumidityData(Map<String, Object> data, ProcessedWeatherData result) {
        List<Map<String, Object>> dataList = safeGetList(data, "data");
        List<BasicDataPoint> weatherData = dataList.stream()
            .filter(Objects::nonNull)
            .filter(item -> {
                Object humiValueObj = item.get("humi");
                if (humiValueObj == null) return false;
                Float humiValue = convertToFloat(humiValueObj);
                return humiValue != null && humiValue >= 0f && humiValue <= 100f;
            })
            .map(item -> new BasicDataPoint(
                convertToFloat(item.get("lon")),
                convertToFloat(item.get("lat")),
                convertToFloat(item.get("humi"))
            ))
            .filter(point -> point.lon != null && point.lat != null && point.value != null)
            .collect(Collectors.toList());
        
        result.weatherData = new JSONArray();
        for (BasicDataPoint point : weatherData) {
            Map<String, Object> pointMap = new HashMap<>();
            pointMap.put("lon", point.lon);
            pointMap.put("lat", point.lat);
            pointMap.put("value", Math.round(point.value * 10) / 10.0); // 保留一位小数
            result.weatherData.add(pointMap);
        }
        
        // 安全获取图例
        result.legend = safeGetLegend(data, "legendhumi");
        result.interval = calculateIntervals(result.weatherData, result.legend, 5.0, "humi");
    }

    /**
     * 处理气压数据
     */
    private static void processPressureData(Map<String, Object> data, ProcessedWeatherData result) {
        List<Map<String, Object>> dataList = safeGetList(data, "data");
        List<BasicDataPoint> weatherData = dataList.stream()
            .filter(Objects::nonNull)
            .filter(item -> {
                Object presValueObj = item.get("pres");
                if (presValueObj == null) return false;
                Float presValue = convertToFloat(presValueObj);
                return presValue != null && presValue != 999999f;
            })
            .map(item -> new BasicDataPoint(
                convertToFloat(item.get("lon")),
                convertToFloat(item.get("lat")),
                convertToFloat(item.get("pres"))
            ))
            .filter(point -> point.lon != null && point.lat != null && point.value != null)
            .collect(Collectors.toList());
        
        result.weatherData = new JSONArray();
        for (BasicDataPoint point : weatherData) {
            Map<String, Object> pointMap = new HashMap<>();
            pointMap.put("lon", point.lon);
            pointMap.put("lat", point.lat);
            pointMap.put("value", Math.round(point.value * 10) / 10.0); // 保留一位小数
            result.weatherData.add(pointMap);
        }

        // 安全获取图例
        result.legend = safeGetLegend(data, "legendpres");
        result.interval = calculateIntervals(result.weatherData, result.legend, 30.0, "pres");
    }

    /**
     * 处理风速数据
     */
    private static void processWindData(Map<String, Object> data, ProcessedWeatherData result) {
        List<Map<String, Object>> dataList = safeGetList(data, "data");
        List<BasicDataPoint> weatherData = dataList.stream()
            .filter(Objects::nonNull)
            .filter(item -> {
                Object windValueObj = item.get("win_10_vel");
                if (windValueObj == null) return false;
                Float windValue = convertToFloat(windValueObj);
                return windValue != null && windValue >= 0f && windValue <= 340f;
            })
            .map(item -> new BasicDataPoint(
                convertToFloat(item.get("lon")),
                convertToFloat(item.get("lat")),
                convertToFloat(item.get("win_10_vel"))
            ))
            .filter(point -> point.lon != null && point.lat != null && point.value != null)
            .collect(Collectors.toList());
        
        result.weatherData = new JSONArray();
        for (BasicDataPoint point : weatherData) {
            Map<String, Object> pointMap = new HashMap<>();
            pointMap.put("lon", point.lon);
            pointMap.put("lat", point.lat);
            pointMap.put("value", Math.round(point.value * 10) / 10.0); // 保留一位小数
            result.weatherData.add(pointMap);
        }

        // 安全获取图例
        result.legend = safeGetLegend(data, "legendwind");
        result.interval = calculateIntervals(result.weatherData, result.legend, 1.0, "win_10_vel");
    }

    /**
     * 处理土壤含水率数据
     */
    private static void processWaterrateData(Map<String, Object> data, ProcessedWeatherData result) {
        List<Map<String, Object>> dataList = safeGetList(data, "data");
        List<BasicDataPoint> weatherData = dataList.stream()
            .filter(Objects::nonNull)
            .filter(item -> {
                Object waterrateValueObj = item.get("waterrate");
                if (waterrateValueObj == null) return false;
                Float waterrateValue = convertToFloat(waterrateValueObj);
                return waterrateValue != null && waterrateValue >= 0f && waterrateValue <= 100f;
            })
            .map(item -> new BasicDataPoint(
                convertToFloat(item.get("lon")),
                convertToFloat(item.get("lat")),
                convertToFloat(item.get("waterrate"))
            ))
            .filter(point -> point.lon != null && point.lat != null && point.value != null)
            .collect(Collectors.toList());
        
        result.weatherData = new JSONArray();
        for (BasicDataPoint point : weatherData) {
            Map<String, Object> pointMap = new HashMap<>();
            pointMap.put("lon", point.lon);
            pointMap.put("lat", point.lat);
            pointMap.put("value", Math.round(point.value * 10) / 10.0); // 保留一位小数
            result.weatherData.add(pointMap);
        }
        
        // 安全获取图例
        result.legend = safeGetLegend(data, "legendwaterrate");
        result.interval = calculateIntervals(result.weatherData, result.legend, 5.0, "waterrate");
    }

    /**
     * 处理地表覆盖物表面湿度数据
     */
    private static void processWaterrateoutData(Map<String, Object> data, ProcessedWeatherData result) {
        List<Map<String, Object>> dataList = safeGetList(data, "data");
        List<BasicDataPoint> weatherData = dataList.stream()
            .filter(Objects::nonNull)
            .filter(item -> {
                Object waterrateoutValueObj = item.get("waterrate_out_plant");
                if (waterrateoutValueObj == null) return false;
                Float waterrateoutValue = convertToFloat(waterrateoutValueObj);
                return waterrateoutValue != null && waterrateoutValue >= 0f && waterrateoutValue <= 100f;
            })
            .map(item -> new BasicDataPoint(
                convertToFloat(item.get("lon")),
                convertToFloat(item.get("lat")),
                convertToFloat(item.get("waterrate_out_plant"))
            ))
            .filter(point -> point.lon != null && point.lat != null && point.value != null)
            .collect(Collectors.toList());
        
        result.weatherData = new JSONArray();
        for (BasicDataPoint point : weatherData) {
            Map<String, Object> pointMap = new HashMap<>();
            pointMap.put("lon", point.lon);
            pointMap.put("lat", point.lat);
            pointMap.put("value", Math.round(point.value * 10) / 10.0); // 保留一位小数
            result.weatherData.add(pointMap);
        }
        
        // 安全获取图例
        result.legend = safeGetLegend(data, "legendwaterrateout");
        result.interval = calculateIntervals(result.weatherData, result.legend, 5.0, "waterrateout");
    }

    /**
     * 处理地表覆盖物内部湿度数据
     */
    private static void processWaterrateinsideData(Map<String, Object> data, ProcessedWeatherData result) {
        List<Map<String, Object>> dataList = safeGetList(data, "data");
        List<BasicDataPoint> weatherData = dataList.stream()
            .filter(Objects::nonNull)
            .filter(item -> {
                Object waterrateinsideValueObj = item.get("waterrate_inside_plant");
                if (waterrateinsideValueObj == null) return false;
                Float waterrateinsideValue = convertToFloat(waterrateinsideValueObj);
                return waterrateinsideValue != null && waterrateinsideValue >= 0f && waterrateinsideValue <= 100f;
            })
            .map(item -> new BasicDataPoint(
                convertToFloat(item.get("lon")),
                convertToFloat(item.get("lat")),
                convertToFloat(item.get("waterrate_inside_plant"))
            ))
            .filter(point -> point.lon != null && point.lat != null && point.value != null)
            .collect(Collectors.toList());
        
        result.weatherData = new JSONArray();
        for (BasicDataPoint point : weatherData) {
            Map<String, Object> pointMap = new HashMap<>();
            pointMap.put("lon", point.lon);
            pointMap.put("lat", point.lat);
            pointMap.put("value", Math.round(point.value * 10) / 10.0); // 保留一位小数
            result.weatherData.add(pointMap);
        }
        
        // 安全获取图例
        result.legend = safeGetLegend(data, "legendwaterrateinside");
        result.interval = calculateIntervals(result.weatherData, result.legend, 5.0, "waterrateinside");
    }

    /**
     * 处理降水数据
     */
    private static void processPrecipitationData(Map<String, Object> data, ProcessedWeatherData result) {
        List<Map<String, Object>> dataList = safeGetList(data, "data");
        List<BasicDataPoint> weatherData = dataList.stream()
            .filter(Objects::nonNull)
            .filter(item -> {
                Object precValueObj = item.get("prec");
                if (precValueObj == null) return false;
                Float precValue = convertToFloat(precValueObj);
                return precValue != null && precValue != 999999f && precValue >= 0f;
            })
            .map(item -> new BasicDataPoint(
                convertToFloat(item.get("lon")),
                convertToFloat(item.get("lat")),
                convertToFloat(item.get("prec"))
            ))
            .filter(point -> point.lon != null && point.lat != null && point.value != null)
            .collect(Collectors.toList());
        
        result.weatherData = new JSONArray();
        for (BasicDataPoint point : weatherData) {
            Map<String, Object> pointMap = new HashMap<>();
            pointMap.put("lon", point.lon);
            pointMap.put("lat", point.lat);
            pointMap.put("value", Math.round(point.value * 10) / 10.0); // 保留一位小数
            result.weatherData.add(pointMap);
        }
        
        // 安全获取图例
        JSONArray legendprecall = safeGetLegend(data, "legendprecall");
        //result.legend = safeGetLegend(data, "legendprec");
        //result.interval = calculateIntervals(result.weatherData, legendprecall, 0.1, "prec");
        result.interval = calculatePrecLegend(result.weatherData, legendprecall);
        //result.interval = legendprecall;
        result.legend = result.interval;
    }

    /**
     * 12小时降雨量
     */
    private static void processRainfall12hourData(Map<String, Object> data, ProcessedWeatherData result) {
        List<Map<String, Object>> dataList = safeGetList(data, "data");
        List<BasicDataPoint> weatherData = dataList.stream()
            .filter(Objects::nonNull)
            .filter(item -> {
                Object precValueObj = item.get("prec");
                if (precValueObj == null) return false;
                Float precValue = convertToFloat(precValueObj);
                return precValue != null && precValue != 999999f && precValue >= 0f;
            })
            .map(item -> new BasicDataPoint(
                convertToFloat(item.get("lon")),
                convertToFloat(item.get("lat")),
                convertToFloat(item.get("prec"))
            ))
            .filter(point -> point.lon != null && point.lat != null && point.value != null)
            .collect(Collectors.toList());
        
        result.weatherData = new JSONArray();
        for (BasicDataPoint point : weatherData) {
            Map<String, Object> pointMap = new HashMap<>();
            pointMap.put("lon", point.lon);
            pointMap.put("lat", point.lat);
            pointMap.put("value", Math.round(point.value * 10) / 10.0); // 保留一位小数
            result.weatherData.add(pointMap);
        }
        
        // 安全获取图例
        JSONArray legendprecall = safeGetLegend(data, "legendprecall");
        //result.legend = safeGetLegend(data, "legendprec");
        //result.interval = calculateIntervals(result.weatherData, legendprecall, 0.1, "prec");
        result.interval = calculatePrecLegend(result.weatherData, legendprecall);
        //result.interval = legendprecall;
        result.legend = result.interval;
    }

    /**
     * 24小时降雨量
     */
    private static void processRainfall24hourData(Map<String, Object> data, ProcessedWeatherData result) {
        List<Map<String, Object>> dataList = safeGetList(data, "data");
        List<BasicDataPoint> weatherData = dataList.stream()
            .filter(Objects::nonNull)
            .filter(item -> {
                Object precValueObj = item.get("prec");
                if (precValueObj == null) return false;
                Float precValue = convertToFloat(precValueObj);
                return precValue != null && precValue != 999999f && precValue >= 0f;
            })
            .map(item -> new BasicDataPoint(
                convertToFloat(item.get("lon")),
                convertToFloat(item.get("lat")),
                convertToFloat(item.get("prec"))
            ))
            .filter(point -> point.lon != null && point.lat != null && point.value != null)
            .collect(Collectors.toList());
        
        result.weatherData = new JSONArray();
        for (BasicDataPoint point : weatherData) {
            Map<String, Object> pointMap = new HashMap<>();
            pointMap.put("lon", point.lon);
            pointMap.put("lat", point.lat);
            pointMap.put("value", Math.round(point.value * 10) / 10.0); // 保留一位小数
            result.weatherData.add(pointMap);
        }
        
        // 安全获取图例
        JSONArray legendprecall = safeGetLegend(data, "legendprecall");
        //result.legend = safeGetLegend(data, "legendprec");
        //result.interval = calculateIntervals(result.weatherData, legendprecall, 0.1, "prec");
        result.interval = calculatePrecLegend(result.weatherData, legendprecall);
        //result.interval = legendprecall;
        result.legend = result.interval;
    }

    /**
     * 10日降雨量
     */
    private static void processRainfall10dayData(Map<String, Object> data, ProcessedWeatherData result) {
        List<Map<String, Object>> dataList = safeGetList(data, "data");
        List<BasicDataPoint> weatherData = dataList.stream()
            .filter(Objects::nonNull)
            .filter(item -> {
                Object precValueObj = item.get("prec");
                if (precValueObj == null) return false;
                Float precValue = convertToFloat(precValueObj);
                return precValue != null && precValue != 999999f && precValue >= 0f;
            })
            .map(item -> new BasicDataPoint(
                convertToFloat(item.get("lon")),
                convertToFloat(item.get("lat")),
                convertToFloat(item.get("prec"))
            ))
            .filter(point -> point.lon != null && point.lat != null && point.value != null)
            .collect(Collectors.toList());
        
        result.weatherData = new JSONArray();
        for (BasicDataPoint point : weatherData) {
            Map<String, Object> pointMap = new HashMap<>();
            pointMap.put("lon", point.lon);
            pointMap.put("lat", point.lat);
            pointMap.put("value", Math.round(point.value * 10) / 10.0); // 保留一位小数
            result.weatherData.add(pointMap);
        }
        
        // 安全获取图例
        // JSONArray legend = safeGetLegend(data, "legendprec");
        // result.legend = calculateLegend(result.weatherData, legend);
        JSONArray legendprecall = safeGetLegend(data, "legendprecall");
        //result.legend = safeGetLegend(data, "legendprec10days");
        //result.interval = calculateIntervals(result.weatherData, legendprecall, 0.1, "prec");
        result.interval = calculatePrecLegend(result.weatherData, legendprecall);
        //result.interval = legendprecall;
        result.legend = result.interval;
    }

    /**
     * 3个月降雨量
     */
    private static void processRainfall3monthData(Map<String, Object> data, ProcessedWeatherData result) {
        List<Map<String, Object>> dataList = safeGetList(data, "data");
        List<BasicDataPoint> weatherData = dataList.stream()
            .filter(Objects::nonNull)
            .filter(item -> {
                Object precValueObj = item.get("prec");
                if (precValueObj == null) return false;
                Float precValue = convertToFloat(precValueObj);
                return precValue != null && precValue != 999999f && precValue >= 0f;
            })
            .map(item -> new BasicDataPoint(
                convertToFloat(item.get("lon")),
                convertToFloat(item.get("lat")),
                convertToFloat(item.get("prec"))
            ))
            .filter(point -> point.lon != null && point.lat != null && point.value != null)
            .collect(Collectors.toList());
        
        result.weatherData = new JSONArray();
        for (BasicDataPoint point : weatherData) {
            Map<String, Object> pointMap = new HashMap<>();
            pointMap.put("lon", point.lon);
            pointMap.put("lat", point.lat);
            pointMap.put("value", Math.round(point.value * 10) / 10.0); // 保留一位小数
            result.weatherData.add(pointMap);
        }
        
        // 安全获取图例
        // JSONArray legend = safeGetLegend(data, "legendprec");
        // result.legend = calculateLegend(result.weatherData, legend);
        JSONArray legendprecall = safeGetLegend(data, "legendprecall");
        //result.legend = safeGetLegend(data, "legendprec3months");
        //result.interval = calculateIntervals(result.weatherData, legendprecall, 0.1, "prec");
        result.interval = calculatePrecLegend(result.weatherData, legendprecall);
        System.out.println("3个月降雨量_interval:"+result.interval.size());
        //result.interval = legendprecall;
        if(result.interval.size()>70){
             JSONArray legendprec3months = safeGetLegend(data, "legendprec3months");
            result.legend = legendprec3months;
        }else{
            result.legend = result.interval;
        }
        
    }

     /**
     * 风场
     */
    private static void processWinddeckData(Map<String, Object> data, ProcessedWeatherData result) {
        List<Map<String, Object>> dataList = safeGetList(data, "data");
        List<BasicWinddeckDataPoint> weatherData = dataList.stream()
            .filter(Objects::nonNull)
            .filter(item -> {
                Object windValueObj = item.get("win_10_vel");
                if (windValueObj == null) return false;
                Float windValue = convertToFloat(windValueObj);
                Object windDirValueObj = item.get("win_10_dir");
                if (windDirValueObj == null) return false;
                Float windDirValue = convertToFloat(windDirValueObj);
                return windValue != null && windValue >= 0f && windValue <= 340f && windDirValue != null && windDirValue >= 0f && windDirValue <= 360f;
            })
            .map(item -> new BasicWinddeckDataPoint(
                convertToFloat(item.get("lon")),
                convertToFloat(item.get("lat")),
                convertToFloat(item.get("win_10_vel")),
                convertToFloat(item.get("win_10_dir"))
            ))
            .filter(point -> point.lon != null && point.lat != null && point.win_10_vel != null && point.win_10_dir != null)
            .collect(Collectors.toList());
        
        result.weatherData = new JSONArray();
        for (BasicWinddeckDataPoint point : weatherData) {
            Map<String, Object> pointMap = new HashMap<>();
            pointMap.put("lon", point.lon);
            pointMap.put("lat", point.lat);
            pointMap.put("win_10_vel", Math.round(point.win_10_vel * 10) / 10.0); // 保留一位小数
            pointMap.put("win_10_dir", Math.round(point.win_10_dir * 10) / 10.0);
            result.weatherData.add(pointMap);
        }

        // 安全获取图例
        result.legend = safeGetLegend(data, "legendwind");
        result.interval = result.legend;
    }

    /**
     * 安全获取列表数据
     */
    @SuppressWarnings("unchecked")
    private static <T> List<T> safeGetList(Map<String, Object> data, String key) {
        Object obj = data.get(key);
        if (obj instanceof List) {
            return (List<T>) obj;
        }
        return new ArrayList<>();
    }

    /**
     * 安全获取图例数据
     */
    private static JSONArray safeGetLegend(Map<String, Object> data, String legendKey) {
        Object obj = data.get(legendKey);
        JSONArray result = new JSONArray();
        
        if (obj == null) {
            return result;
        }
        
        try {
            if ("legendtem".equals(legendKey) || "legendtemall".equals(legendKey) && obj instanceof List) {
                List<LegendTemConfig> legendData = (List<LegendTemConfig>) obj;
                for (LegendTemConfig config : legendData) {
                    Map<String, Object> legendItem = new HashMap<>();
                    legendItem.put("value", config.getValue());
                    legendItem.put("color", config.getColor());
                    result.add(legendItem);
                }
            } else if ("legendwind".equals(legendKey) && obj instanceof List) {
                List<LegendWindConfig> legendData = (List<LegendWindConfig>) obj;
                for (LegendWindConfig config : legendData) {
                    Map<String, Object> legendItem = new HashMap<>();
                    legendItem.put("value", config.getValue());
                    legendItem.put("color", config.getColor());
                    result.add(legendItem);
                }
            } else if ("legendhumi".equals(legendKey) && obj instanceof List) {
                List<LegendHumiConfig> legendData = (List<LegendHumiConfig>) obj;
                for (LegendHumiConfig config : legendData) {
                    Map<String, Object> legendItem = new HashMap<>();
                    legendItem.put("value", config.getValue());
                    legendItem.put("color", config.getColor());
                    result.add(legendItem);
                }
            } else if ("legendprec".equals(legendKey) && obj instanceof List) {
                List<LegendPrecConfig> legendData = (List<LegendPrecConfig>) obj;
                for (LegendPrecConfig config : legendData) {
                    Map<String, Object> legendItem = new HashMap<>();
                    legendItem.put("value", config.getValue());
                    legendItem.put("color", config.getColor());
                    result.add(legendItem);
                }
            } else if ("legendpres".equals(legendKey) && obj instanceof List) {
                List<LegendPresConfig> legendData = (List<LegendPresConfig>) obj;
                for (LegendPresConfig config : legendData) {
                    Map<String, Object> legendItem = new HashMap<>();
                    legendItem.put("value", config.getValue());
                    legendItem.put("color", config.getColor());
                    result.add(legendItem);
                }
             } else if ("legendwaterrate".equals(legendKey) && obj instanceof List) {
                List<LegendWaterrateConfig> legendData = (List<LegendWaterrateConfig>) obj;
                for (LegendWaterrateConfig config : legendData) {
                    Map<String, Object> legendItem = new HashMap<>();
                    legendItem.put("value", config.getValue());
                    legendItem.put("color", config.getColor());
                    result.add(legendItem);
                }
             } else if ("legendwaterrateout".equals(legendKey) && obj instanceof List) {
                List<LegendWaterrateoutConfig> legendData = (List<LegendWaterrateoutConfig>) obj;
                for (LegendWaterrateoutConfig config : legendData) {
                    Map<String, Object> legendItem = new HashMap<>();
                    legendItem.put("value", config.getValue());
                    legendItem.put("color", config.getColor());
                    result.add(legendItem);
                }
             } else if ("legendwaterrateinside".equals(legendKey) && obj instanceof List) {
                List<LegendWaterrateinsideConfig> legendData = (List<LegendWaterrateinsideConfig>) obj;
                for (LegendWaterrateinsideConfig config : legendData) {
                    Map<String, Object> legendItem = new HashMap<>();
                    legendItem.put("value", config.getValue());
                    legendItem.put("color", config.getColor());
                    result.add(legendItem);
                }
            } else if ("legendprec10days".equals(legendKey) && obj instanceof List) {
                List<LegendPrec10daysConfig> legendData = (List<LegendPrec10daysConfig>) obj;
                for (LegendPrec10daysConfig config : legendData) {
                    Map<String, Object> legendItem = new HashMap<>();
                    legendItem.put("value", config.getValue());
                    legendItem.put("color", config.getColor());
                    result.add(legendItem);

                }
            } else if ("legendprec3months".equals(legendKey) && obj instanceof List) {
                List<LegendPrec3monthsConfig> legendData = (List<LegendPrec3monthsConfig>) obj;
                for (LegendPrec3monthsConfig config : legendData) {
                    Map<String, Object> legendItem = new HashMap<>();
                    legendItem.put("value", config.getValue());
                    legendItem.put("color", config.getColor());
                    result.add(legendItem);
                }
            } else if ("legendprecall".equals(legendKey) && obj instanceof List) {
                List<LegendPrecAllConfig> legendData = (List<LegendPrecAllConfig>) obj;
                for (LegendPrecAllConfig config : legendData) {
                    Map<String, Object> legendItem = new HashMap<>();
                    legendItem.put("value", config.getValue());
                    legendItem.put("color", config.getColor());
                    result.add(legendItem);
                }
            } else if (obj instanceof JSONArray) {
                return (JSONArray) obj;
            } else if (obj instanceof String) {
                String legendStr = ((String) obj).trim();
                if (!legendStr.isEmpty() && legendStr.startsWith("[")) {
                    return JSONArray.parseArray(legendStr);
                }
            }
        } catch (Exception e) {
            System.err.println("Error parsing legend data for key " + legendKey + ": " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 计算合适的数据区间
     */
    private static JSONArray calculateIntervals(JSONArray dataPoints, 
                                        JSONArray legend,
                                        double defaultIntervalStep, String type) {
        if (dataPoints == null || dataPoints.isEmpty() || legend == null || legend.isEmpty()) {
            return new JSONArray();
        }

        // 从数据点中提取所有值
        List<Double> values = new ArrayList<>();
        for (int i = 0; i < dataPoints.size(); i++) {
            Object item = dataPoints.get(i);
            if (item instanceof Map) {
                Map<String, Object> mapItem = (Map<String, Object>) item;
                Double value = convertToDouble(mapItem.get("value"));
                if (value != null) {
                    values.add(value);
                }
            }
        }

        if (values.isEmpty()) {
            return new JSONArray();
        }

        double minValue = Collections.min(values);
        double maxValue = Collections.max(values);

        // 从图例中提取所有值
        List<Double> legendValues = new ArrayList<>();
        List<Object> legendItems = new ArrayList<>();
        
        for (int i = 0; i < legend.size(); i++) {
            Object item = legend.get(i);
            if (item instanceof Map) {
                Map<String, Object> mapItem = (Map<String, Object>) item;
                Double value = convertToDouble(mapItem.get("value"));
                if (value != null) {
                    legendValues.add(value);
                    legendItems.add(item); // 保存完整的图例项
                }
            }
        }

        if (legendValues.isEmpty()) {
            return new JSONArray();
        }

        // 计算区间步长
        double intervalStep = defaultIntervalStep;
        if (legendValues.size() > 1) {
            intervalStep = legendValues.get(1) - legendValues.get(0);
        }

        // 扩展区间范围，确保包含所有数据点
        double expandedMin = Math.floor(minValue - intervalStep);
        double expandedMax = Math.ceil(maxValue + intervalStep);
        if("humi".equals(type) || "waterrate".equals(type) || "waterrateout".equals(type) || "waterrateinside".equals(type)){
            //湿度
            expandedMin = Math.floor(minValue / 5) * 5;
            expandedMax = Math.ceil(maxValue / 5) * 5;
        }
        if("pres".equals(type)){
            //气压
            // 获取小于 minValue 在 preslegend 中最接近的值
            double closestLower = minValue;
            List<Map<String, Object>> lowerValues = new ArrayList<>();
            for (int i = 0; i < legend.size(); i++) {
                Object item = legend.get(i);
                if (item instanceof Map) {
                    Map<String, Object> mapItem = (Map<String, Object>) item;
                    Double value = convertToDouble(mapItem.get("value"));
                    if (value != null && value < minValue) {
                        lowerValues.add(mapItem);
                    }
                }
            }

            if (!lowerValues.isEmpty()) {
                lowerValues.sort((a, b) -> {
                    Double aValue = convertToDouble(a.get("value"));
                    Double bValue = convertToDouble(b.get("value"));
                    return Double.compare(bValue, aValue); // 降序排列
                });
                
                Map<String, Object> closestLowerItem = lowerValues.get(0);
                Double closestLowerValue = convertToDouble(closestLowerItem.get("value"));
                if (closestLowerValue != null) {
                    closestLower = closestLowerValue;
                }
            }

            // 获取大于 maxValue 在 preslegend 中最接近的值
            double closestHigher = maxValue;
            List<Map<String, Object>> higherValues = new ArrayList<>();
            for (int i = 0; i < legend.size(); i++) {
                Object item = legend.get(i);
                if (item instanceof Map) {
                    Map<String, Object> mapItem = (Map<String, Object>) item;
                    Double value = convertToDouble(mapItem.get("value"));
                    if (value != null && value > maxValue) {
                        higherValues.add(mapItem);
                    }
                }
            }

            if (!higherValues.isEmpty()) {
                higherValues.sort((a, b) -> {
                    Double aValue = convertToDouble(a.get("value"));
                    Double bValue = convertToDouble(b.get("value"));
                    return Double.compare(aValue, bValue); // 升序排列
                });
                
                Map<String, Object> closestHigherItem = higherValues.get(0);
                Double closestHigherValue = convertToDouble(closestHigherItem.get("value"));
                if (closestHigherValue != null) {
                    closestHigher = closestHigherValue;
                }
            }
            
            expandedMin = closestLower;
            expandedMax = closestHigher;
        }

        double legendMin = Collections.min(legendValues);
        double legendMax = Collections.max(legendValues);

        // 确保扩展后的区间在legend范围内
        double expandedMinFinal = Math.max(expandedMin, legendMin);
        double expandedMaxFinal = Math.min(expandedMax, legendMax);

        //打印日志
        System.out.println("minValue: " + minValue);
        System.out.println("maxValue: " + maxValue);
        System.out.println("expandedMin: " + expandedMin);
        System.out.println("expandedMax: " + expandedMax);
        System.out.println("legendMin: " + legendMin);
        System.out.println("legendMax: " + legendMax);
        System.out.println("expandedMinFinal: " + expandedMinFinal);
        System.out.println("expandedMaxFinal: " + expandedMaxFinal);

        // 创建包含完整图例信息的区间数组
        JSONArray intervals = new JSONArray();
        for (int i = 0; i < legendValues.size(); i++) {
            Double value = legendValues.get(i);
            if (value >= expandedMinFinal && value <= expandedMaxFinal) {
                // 添加完整的图例项，包括value和color
                intervals.add(legendItems.get(i));
            }
        }

        return intervals;
    }

    /**
     * 根据降水数据的最大值截取图例
     * 
     * @param weatherData 天气数据点数组
     * @param legend 原始图例数组
     * @return 截取后的新图例数组，值保留一位小数，始终从0开始
     */
    private static JSONArray calculatePrecLegend(JSONArray weatherData, JSONArray legend) {
        if (weatherData == null || weatherData.isEmpty() || legend == null || legend.isEmpty()) {
            return legend != null ? legend : new JSONArray();
        }

        // 提取所有降水数据值
        List<Double> values = new ArrayList<>();
        for (int i = 0; i < weatherData.size(); i++) {
            Object item = weatherData.get(i);
            if (item instanceof Map) {
                Map<String, Object> mapItem = (Map<String, Object>) item;
                Double value = convertToDouble(mapItem.get("value"));
                if (value != null && value >= 0) { // 降水数据应>=0
                    values.add(value);
                }
            }
        }

        if (values.isEmpty()) {
            return legend;
        }

        // 计算实际的最大值，最小值始终为0
        double minValue = 0.0; // 始终从0开始
        double maxValue = Collections.max(values);
        
        // 扩展一位：找到紧邻的更小和更大值
        double extendedMinValue = 0.0; // 始终从0开始
        double extendedMaxValue = Math.round(maxValue * 10) / 10.0;
        
        List<Double> legendValues = new ArrayList<>();
        for (int i = 0; i < legend.size(); i++) {
            Object legendItem = legend.get(i);
            if (legendItem instanceof Map) {
                Map<String, Object> mapItem = (Map<String, Object>) legendItem;
                Double legendValue = convertToDouble(mapItem.get("value"));
                if (legendValue != null) {
                    legendValues.add(legendValue);
                }
            }
        }
        
        if (!legendValues.isEmpty()) {
            // 对图例值进行排序
            Collections.sort(legendValues);
            
            // 找到紧邻的更大值作为扩展最大值
            for (int i = 0; i < legendValues.size(); i++) {
                if (legendValues.get(i) > maxValue) {
                    extendedMaxValue = legendValues.get(i);
                    break;
                }
            }
        }
        
        System.out.println("PrecLegend - Min value: " + extendedMinValue + ", Max value: " + extendedMaxValue);

        // 根据扩展后的数据范围筛选图例，并对值进行格式化处理
        JSONArray result = new JSONArray();
        for (int i = 0; i < legend.size(); i++) {
            Object legendItem = legend.get(i);
            if (legendItem instanceof Map) {
                Map<String, Object> mapItem = (Map<String, Object>) legendItem;
                Double legendValue = convertToDouble(mapItem.get("value"));
                // 使用扩展后的最小值(始终为0)和最大值
                if (legendValue != null && legendValue >= extendedMinValue && legendValue <= extendedMaxValue) {
                    // 创建一个新的图例项，保证value保留一位小数
                    Map<String, Object> newItem = new HashMap<>();
                    for (Map.Entry<String, Object> entry : mapItem.entrySet()) {
                        if ("value".equals(entry.getKey())) {
                            // 对value进行格式化，保留一位小数
                            newItem.put("value", Math.round(legendValue * 10) / 10.0);
                        } else {
                            newItem.put(entry.getKey(), entry.getValue());
                        }
                    }
                    result.add(newItem);
                }
            }
        }

        // 打印获得的图例数组的最大值和最小值
        if (!result.isEmpty()) {
            List<Double> resultLegendValues = new ArrayList<>();
            for (int i = 0; i < result.size(); i++) {
                Object item = result.get(i);
                if (item instanceof Map) {
                    Map<String, Object> mapItem = (Map<String, Object>) item;
                    Double value = convertToDouble(mapItem.get("value"));
                    if (value != null) {
                        resultLegendValues.add(value);
                    }
                }
            }
            
            if (!resultLegendValues.isEmpty()) {
                double resultMinValue = Collections.min(resultLegendValues);
                double resultMaxValue = Collections.max(resultLegendValues);
                System.out.println("PrecLegend - Min value: " + resultMinValue + ", Max value: " + resultMaxValue);
            }
        } else {
            System.out.println("PrecLegend - No matching legend items found");
        }

        return result.isEmpty() ? legend : result;
    }
    
    /**
     * 根据天气数据和原始图例计算新的图例
     * 
     * @param weatherData 天气数据点数组
     * @param legend 原始图例数组
     * @return 新的图例数组，根据数据的最大值和最小值重新计算区间
     */
    private static JSONArray calculateLegend(JSONArray weatherData, JSONArray legend) {
        if (weatherData == null || weatherData.isEmpty() || legend == null || legend.isEmpty()) {
            return legend != null ? legend : new JSONArray();
        }

        // 提取所有数据值
        List<Double> values = new ArrayList<>();
        for (int i = 0; i < weatherData.size(); i++) {
            Object item = weatherData.get(i);
            if (item instanceof Map) {
                Map<String, Object> mapItem = (Map<String, Object>) item;
                Double value = convertToDouble(mapItem.get("value"));
                if (value != null) {
                    values.add(value);
                }
            }
        }

        // 如果没有有效值，返回原始图例
        if (values.isEmpty()) {
            return legend;
        }

        // 计算实际的最大值和最小值
        double originalMinValue = Collections.min(values);
        double originalMaxValue = Collections.max(values);

        // 获取原始图例的数量
        int legendCount = legend.size();

        // 使用科学计算方法确定合适的minValue、maxValue和步长
        double[] calculatedParams = calculateOptimalRangeAndStep(originalMinValue, originalMaxValue, legendCount);
        double minValue = calculatedParams[0];
        double maxValue = calculatedParams[1];
        double step = calculatedParams[2];

        System.out.println("originalMinValue: " + originalMinValue);
        System.out.println("originalMaxValue: " + originalMaxValue);
        System.out.println("adjustedMinValue: " + minValue);
        System.out.println("adjustedMaxValue: " + maxValue);
        System.out.println("step: " + step);

        // 构建新的图例
        JSONArray newLegend = new JSONArray();
        
        // 遍历原始图例，创建新的图例项
        for (int i = 0; i < legendCount; i++) {
            Object originalLegendItem = legend.get(i);
            
            // 复制原始图例项结构
            if (originalLegendItem instanceof Map) {
                Map<String, Object> originalMap = (Map<String, Object>) originalLegendItem;
                Map<String, Object> newLegendItem = new HashMap<>();
                
                // 保留除value外的所有属性（如color）
                for (Map.Entry<String, Object> entry : originalMap.entrySet()) {
                    if (!"value".equals(entry.getKey())) {
                        newLegendItem.put(entry.getKey(), entry.getValue());
                    }
                }
                
                // 计算并设置新的value（使用区间的上限值）
                double newValue = minValue + (i) * step;
                
                // 确保最后一个区间至少覆盖最大值
                if (i == legendCount - 1 && newValue < originalMaxValue) {
                    newValue = Math.max(maxValue, newValue);
                }
                
                // 根据原始图例值的类型决定新值的类型
                Object originalValue = originalMap.get("value");
                if (originalValue instanceof Integer) {
                    newLegendItem.put("value", (int) Math.round(newValue));
                } else {
                    newLegendItem.put("value", Math.round(newValue * 10.0) / 10.0); // 保留2位小数
                }
                
                newLegend.add(newLegendItem);
            } else {
                // 如果原始图例项不是Map类型，则直接添加
                newLegend.add(originalLegendItem);
            }
        }

        return newLegend;
    }

   /**
     * 科学计算最优范围和步长，确保区间完全覆盖数据范围且更贴近实际数据
     * 
     * @param minValue 最小值
     * @param maxValue 最大值
     * @param legendCount 图例数量
     * @return 包含[minValue, maxValue, step]的数组
     */
    private static double[] calculateOptimalRangeAndStep(double minValue, double maxValue, int legendCount) {
        // 计算数据范围
        double range = maxValue - minValue;
        
        // 如果范围为0，则设置一个默认范围
        if (range == 0) {
            minValue = minValue - 5;
            maxValue = maxValue + 5;
            range = 10;
        }
        
        // 根据范围确定合适的步长
        double step = calculateNiceStep(range, legendCount);
        
        // 计算更贴近实际数据的调整值
        double adjustedMinValue = Math.floor(minValue / step) * step;
        double adjustedMaxValue = Math.ceil(maxValue / step) * step;
        
        // 智能确定有意义的最小阈值
        // 规则：如果步长大于等于某个值，则有意义的最小阈值为该步长值
        // 否则，有意义的最小阈值为步长的一半
        double meaningfulMinThreshold = calculateMeaningfulMinThreshold(step);
        
        // 应用有意义的最小阈值
        if (minValue > meaningfulMinThreshold && adjustedMinValue < meaningfulMinThreshold) {
            adjustedMinValue = Math.floor(meaningfulMinThreshold / step) * step;
            
            // 确保调整后的最小值不会超过实际最小值太多
            if (adjustedMinValue > minValue) {
                adjustedMinValue = Math.floor(minValue / step) * step;
            }
        }
        
        // 检查是否需要进一步调整以更贴近数据
        if (minValue - adjustedMinValue > step) {
            double candidate = Math.ceil(minValue / step) * step - step;
            if (candidate <= minValue) {
                adjustedMinValue = candidate;
            }
        }
        
        if (adjustedMaxValue - maxValue > step) {
            double candidate = Math.floor(maxValue / step) * step + step;
            if (candidate >= maxValue) {
                adjustedMaxValue = candidate;
            }
        }
        
        // 确保范围仍然覆盖所有数据
        if (adjustedMinValue > minValue) {
            adjustedMinValue = Math.floor(minValue / step) * step;
        }
        
        if (adjustedMaxValue < maxValue) {
            adjustedMaxValue = Math.ceil(maxValue / step) * step;
        }
        
        // 确保区间数量合理
        int intervalCount = (int) Math.ceil((adjustedMaxValue - adjustedMinValue) / step);
        if (intervalCount > legendCount * 2) {
            adjustedMaxValue = adjustedMinValue + step * legendCount;
        }
        
        return new double[] {adjustedMinValue, adjustedMaxValue, step};
    }

    /**
     * 根据步长计算有意义的最小阈值
     * 
     * @param step 步长
     * @return 有意义的最小阈值
     */
    private static double calculateMeaningfulMinThreshold(double step) {
        // 如果步长大于等于50，则有意义的最小阈值为50
        if (step >= 50) {
            return 50.0;
        }
        // 如果步长大于等于10，则有意义的最小阈值为10
        else if (step >= 10) {
            return 10.0;
        }
        // 如果步长大于等于5，则有意义的最小阈值为5
        else if (step >= 5) {
            return 5.0;
        }
        // 如果步长大于等于1，则有意义的最小阈值为1
        else if (step >= 1) {
            return 1.0;
        }
        // 如果步长小于1，则有意义的最小阈值为步长的一半
        else {
            return step / 2;
        }
    }

    /**
     * 计算合适的"规整"步长值
     * 
     * @param range 数据范围
     * @param legendCount 图例数量
     * @return 合适的步长值
     */
    private static double calculateNiceStep(double range, int legendCount) {
        // 计算原始步长
        double rawStep = range / legendCount;
        
        // 计算步长的数量级
        double magnitude = Math.pow(10, Math.floor(Math.log10(rawStep)));
        
        // 可用的规整步长因子
        double[] niceFractions = {1, 2, 5, 10};
        
        // 找到最适合的规整步长
        double bestStep = rawStep;
        double minDifference = Double.MAX_VALUE;
        
        for (double fraction : niceFractions) {
            double step = fraction * magnitude;
            double difference = Math.abs(step - rawStep);
            if (difference < minDifference) {
                minDifference = difference;
                bestStep = step;
            }
            
            // 也检查更小一个数量级的情况
            step = fraction * magnitude / 10;
            difference = Math.abs(step - rawStep);
            if (difference < minDifference) {
                minDifference = difference;
                bestStep = step;
            }
        }
        
        return bestStep;
    }


    /**
     * 将Object转换为Float
     */
    private static Float convertToFloat(Object obj) {
        if (obj == null) return null;
        try {
            if (obj instanceof Number) {
                return ((Number) obj).floatValue();
            }
            if (obj instanceof String) {
                String str = ((String) obj).trim();
                // 处理可能的非法字符
                if (str.isEmpty()) {
                    return null;
                }
                // 移除可能的非数字字符（除了数字、小数点、负号）
                str = str.replaceAll("[^0-9.-]", "");
                if (str.isEmpty() || "-".equals(str) || ".".equals(str)) {
                    return null;
                }
                return Float.parseFloat(str);
            }
        } catch (NumberFormatException e) {
            // 记录调试信息
            System.err.println("Failed to convert to float: " + obj);
        }
        return null;
    }

   /**
     * 将Object转换为Double
     */
    private static Double convertToDouble(Object obj) {
        if (obj == null) return null;
        try {
            if (obj instanceof Number) {
                return ((Number) obj).doubleValue();
            }
            if (obj instanceof String) {
                String str = ((String) obj).trim();
                // 处理可能的非法字符
                if (str.isEmpty()) {
                    return null;
                }
                // 移除可能的非数字字符（除了数字、小数点、负号）
                str = str.replaceAll("[^0-9.-]", "");
                if (str.isEmpty() || "-".equals(str) || ".".equals(str)) {
                    return null;
                }
                return Double.parseDouble(str);
            }
        } catch (NumberFormatException e) {
            // 记录调试信息
            System.err.println("Failed to convert to double: " + obj);
        }
        return null;
    }
    // 数据类定义
    public static class ProcessedWeatherData {
        public JSONArray weatherData = new JSONArray();
        public JSONArray legend = new JSONArray();
        public JSONArray interval = new JSONArray();
    }

    public static class BasicDataPoint {
        public Float lon;
        public Float lat;
        public Float value;

        public BasicDataPoint(Float lon, Float lat, Float value) {
            this.lon = lon;
            this.lat = lat;
            this.value = value;
        }
    }

    public static class BasicWinddeckDataPoint {
        public Float lon;
        public Float lat;
        public Float win_10_vel;
        public Float win_10_dir;

        public BasicWinddeckDataPoint(Float lon, Float lat, Float win_10_vel, Float win_10_dir) {
            this.lon = lon;
            this.lat = lat;
            this.win_10_vel = win_10_vel;
            this.win_10_dir = win_10_dir;
        }
    }

    /**
     * 根据时间类型计算时间范围
     * @param type 时间类型 (rainfall12hour, rainfall24hour, rainfall10day, rainfall3month)
     * @return 包含开始时间和结束时间的Map
     */
    public static Map<String, String> getljtime(String type) {
        // 参数验证
        if (type == null || type.isEmpty()) {
            throw new IllegalArgumentException("Time type cannot be null or empty");
        }
        
        // 使用现代日期时间API
        LocalDateTime endTime = LocalDateTime.now().withMinute(0).withSecond(0).withNano(0);
        LocalDateTime startTime = endTime;
        
        // 处理开始时间（根据不同的时间类型计算）
        switch (type) {
            case "rainfall12hour":
                // 12小时前的时间
                startTime = endTime.minusHours(12);
                break;
            case "rainfall24hour":
                // 24小时前的时间
                startTime = endTime.minusHours(24);
                break;
            case "rainfall10day":
                // 10天前的时间
                startTime = endTime.minusDays(10);
                break;
            case "rainfall3month":
                // 3个月前的时间
                startTime = endTime.minusMonths(3);
                break;
            default:
                throw new IllegalArgumentException("Unsupported time type: " + type);
        }
        
        // 格式化时间
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
        String etime = endTime.format(formatter);
        String btime = startTime.format(formatter);
        
        // 返回包含开始时间和结束时间的Map
        Map<String, String> result = new HashMap<>();
        result.put("btime", btime);
        result.put("etime", etime);
        
        return result;
    }

     public static JSONArray getPrecipitationLegend() {
        return JSONArray.parseArray("[" +
            "{\"value\":0,\"color\":\"#e5ffe4\"}," +
            "{\"value\":0.5,\"color\":\"#bff6bb\"}," +
            "{\"value\":1,\"color\":\"#8feeca\"}," +
            "{\"value\":1.5,\"color\":\"#BBFFFF\"}," +
            "{\"value\":10,\"color\":\"#A6EEFF\"}," +
            "{\"value\":15,\"color\":\"#91DDFF\"}," +
            "{\"value\":20,\"color\":\"#7CCCFF\"}," +
            "{\"value\":25,\"color\":\"#67BBFF\"}," +
            "{\"value\":30,\"color\":\"#52AAFF\"}," +
            "{\"value\":35,\"color\":\"#3D99FF\"}," +
            "{\"value\":40,\"color\":\"#2888FF\"}," +
            "{\"value\":45,\"color\":\"#1377FF\"}," +
            "{\"value\":50,\"color\":\"#0066FF\"}," +
            "{\"value\":55,\"color\":\"#0055EE\"}," +
            "{\"value\":60,\"color\":\"#0044DD\"}," +
            "{\"value\":65,\"color\":\"#0033CC\"}," +
            "{\"value\":70,\"color\":\"#0022BB\"}," +
            "{\"value\":75,\"color\":\"#0011AA\"}," +
            "{\"value\":80,\"color\":\"#0008AA\"}," +
            "{\"value\":85,\"color\":\"#0006AA\"}," +
            "{\"value\":90,\"color\":\"#0004AA\"}," +
            "{\"value\":95,\"color\":\"#0001AA\"}," +
            "{\"value\":100,\"color\":\"#000088\"}" +
            "]");
    }

        public static JSONArray gettestdata() {
        return JSONArray.parseArray("[" +
            "{\"value\": 20.2,\r\n" + "}," +
            "{\"value\": 1,\r\n" + "}," +
            "{\"value\": 1,\r\n" + "}," +
            "{ \"value\": 0,\r\n" + "}," +
            "]");
    }



    public static void main(String[] args) {
        // Map<String, String> result12 = WeatherDataProcessor.getljtime("rainfall12hour");
        // System.out.println(result12);
        
        // Map<String, String> result24 = WeatherDataProcessor.getljtime("rainfall24hour");
        // System.out.println(result24);
        
        // Map<String, String> result10 = WeatherDataProcessor.getljtime("rainfall10day");
        // System.out.println(result10);
        
        // Map<String, String> result3m = WeatherDataProcessor.getljtime("rainfall3month");
        // System.out.println(result3m);

        JSONArray legendprec = getPrecipitationLegend();
        JSONArray testdata = gettestdata();

        JSONArray newlegend = WeatherDataProcessor.calculatePrecLegend(testdata, legendprec);
        System.out.println(newlegend.toString());

    }
}